import React, { useContext, useEffect, useState } from "react";
import classes from "./Cart.module.css";
import iconImg from "../../asset/bag.png";
import CardCountext from "../../store/CardCountext";
import CartDetail from "./CartDetail/CartDetail";
import Checkout from "./Checkout/Checkout";

function Cart() {
    const ctx = useContext(CardCountext);
    const totalAmountDOM = (
        <span className={classes.totalAmount}>{ctx.totalAmount}</span>
    );
    const priceDOM = <span className={classes.price}>{ctx.totalPrice}</span>;
    const noMealDOM = <span className={classes.noMeal}>未选购商品</span>;

    const [showDetails, setShowDetails] = useState(false);
    const [showCheckout, setShowCheckout] = useState(false);

    //切换购物车显隐
    const toggleDeatailsHandler = () => {
        if (ctx.totalAmount === 0) {
            setShowDetails(false);
            return
        };
        setShowDetails((prevStatus) => !prevStatus);
    };

    //切换结算页面显隐
    const showCheckoutHandler = () => {
        if(ctx.totalAmount === 0) return;
        setShowCheckout(true);
    }

    //  
    const hideCheckoutHandler = () => {
        setShowCheckout(false);
    }

    //判断购物车和结算页面是否为空
    useEffect(() => {
        if (ctx.totalAmount === 0) {
            setShowDetails(false);
            setShowCheckout(false)
        };
    },[ctx])


    return (
        <div
            className={classes.cart}
            onClick={toggleDeatailsHandler}
        >   
            {/* 结算页面 */}
            {showCheckout && <Checkout onHide={hideCheckoutHandler}/>}

            {/* 购物车详细 */}
            {showDetails && <CartDetail/>}

            {/* //购物车栏位 */}
            <div className={classes.icon}>
                <img className={classes.iconImg} src={iconImg} alt="" />
                {ctx.totalAmount === 0 ? null : totalAmountDOM}
            </div>
            {ctx.totalAmount === 0 ? noMealDOM : priceDOM}
            <button
                onClick={showCheckoutHandler}
                className={`${classes.button} ${
                    ctx.totalAmount === 0 ? classes.disabled : ""
                }`}
            >
                去结算
            </button>
        </div>
    );
}

export default Cart;
